﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GrapplingTongue : MonoBehaviour
{
    public Transform tongueTip, cameraTip, player;
    public LayerMask whatIsGrappleable; // 设置layer

    private LineRenderer lr;
    private Vector2 grapplePoint; // 要抓的点
    private SpringJoint2D joint;

    private float maxDistance = 2f;

    private void Awake ()
    {
        lr = GetComponent<LineRenderer> ();

    }

    // 检测是否开始射线
    private void Update ()
    {
        // 判断
#if UNITY_EDITOR
        if (Input.GetMouseButtonDown (0))
        {
            StartGrapple ();
        }
        else if (Input.GetMouseButtonUp (0))
        {
            StopGrapple ();
        }
#else // 手机端
        if (Input.touchCount > 0)
        {
            StartGrapple ();
        }
        else if(Input.touchCount == 0)
        {
            StopGrapple ();
        }
#endif
    }
    // called after Update
    private void LateUpdate ()
    {
        DrawRope ();
    }

    /// <summary>
    /// Call whenever we want to start a grapple
    /// 在每次想要抓取时调用
    /// </summary>
    private void StartGrapple ()
    {
        RaycastHit2D hit;
        // 起点 终点
        Vector2 endpos = MousePos.MouseFollow ();
        hit = Physics2D.Raycast (origin: cameraTip.position, direction: endpos, maxDistance, whatIsGrappleable);
        if (hit.collider != null)
        {
            grapplePoint = endpos;
            joint = player.gameObject.GetComponent<SpringJoint2D> (); // 添加一个接头
            if(joint == null) joint = player.gameObject.AddComponent<SpringJoint2D> ();
            joint.connectedAnchor = grapplePoint;

            float distanceFromPoint = Vector2.Distance (a: player.position, b: grapplePoint);
            joint.distance = distanceFromPoint * 0.6f;
            joint.dampingRatio = 1f;
            joint.frequency = 1.5f;

            lr.positionCount = 2;

        }

    }

    void DrawRope()
    {
        if (!joint) return;
        lr.SetPosition (index: 0, tongueTip.position);
        lr.SetPosition (index: 1, new Vector3(grapplePoint.x, grapplePoint.y, transform.position.z));
    }

    /// <summary>
    /// Call whenever we want to stop a grapple
    /// </summary>
    private void StopGrapple ()
    {
        lr.positionCount = 0;
        Destroy (joint);
    }

    public bool IsGrapping()
    {
        return joint != null;
    }

    public Vector3 GetGrappingPoint()
    {
        return new Vector3(grapplePoint.x, grapplePoint.y, transform.position.z);
    }

}



